<?php
/**
 * Description: 创建系统订单
 * User: devforma
 * Date: 15/5/29
 * Time: 13:43
 */

class GenOrder implements iController {

    private $now = 0;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        //参数校验
        if (empty($queryArgs['product_id']) || !is_numeric($queryArgs['product_id']) ||
            empty($queryArgs['product_type']) ||
            empty($queryArgs['product_count']) || !is_numeric($queryArgs['product_count']) ||
            empty($queryArgs['terminal_type'])) {

            return genOutput(1000);
        }

        $this->now = time();

        $typeRel = array(
            'live_course' => 'zhiboke',
            'vod_course' => 'course',
            'interview' => 'interview'
        );

        //检测是否已购买
        $purchased = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:pid
        AND `product_type`=:ptype', array(
            ':uid' => $queryArgs['user_id'],
            ':pid' => $queryArgs['product_id'],
            ':ptype' => $typeRel[$queryArgs['product_type']]
        ));

        if ($purchased)
            return genOutput(1000);

        //计算价格
        switch ($queryArgs['product_type']) {
            case 'live_course':

                $personsNum = $cmsdb->getVar('SELECT COUNT(*) FROM `relation_user_product` WHERE `product_type`="zhiboke" AND `product_id`=:pid',
                    array(':pid' => $queryArgs['product_id']));

                //获取创建订单需要的课程信息
                $exist = getOrderCourseInfo($queryArgs['product_id']);
                $exist->name = $exist->course_name;

                //购课人数限制
                if (empty($exist) || ($exist->student_limit != -1 && $exist->student_limit <= $personsNum)) {
                    return genOutput(1001);
                }

                //抢购课程禁止超数
                if ($exist->is_limited) {
                    $validOrderNum = getValidOrderNum($exist->id, date('Y-m-d H:i:s', $this->now)); //未支付的有效订单数

                    if ($exist->student_limit != -1 && $exist->student_limit <= $personsNum + $validOrderNum)
                        return genOutput(8002);
                }

                //未开售课程禁止提前购买
                if ($exist->time_can_purchase != '0000-00-00 00:00:00' && strtotime($exist->time_can_purchase) > $this->now) {
                    return genOutput(1001);
                }

                //下架的课程禁止购买
                $outdate = $exist->end_day == '0000-00-00 00:00:00' ? $exist->class_endtime : $exist->end_day;
                if ($exist->publish_status == 'draft' || strtotime($outdate) < $this->now) {
                    return genOutput(1001);
                }

                break;

            case 'vod_course':
                $exist = $cmsdb->getRow('SELECT `id`, `current_price` AS price, `course_name` AS name
                FROM `data_vod_course` WHERE `id`=:cid', array(':cid' => $queryArgs['product_id']));
                break;

            case 'interview':
                $exist = $cmsdb->getRow('SELECT `id`, `product_price` AS price, `product_name` AS name
                FROM `conf_product` WHERE `id`=:id', array(':id' => $queryArgs['product_id']));
                break;

            //没有该种类型商品
            default:
                return genOutput(1000);
        }

        if (empty($exist)) //没有该商品
            return genOutput(1000);

        $price = floatval($exist->price); //价格
        $isFree = empty($price); //是否免费

        $inviteUser = empty($queryArgs['invite_code']) ? 0 : hexdec($queryArgs['invite_code']);

        $now = time(); //当前时间
        $order = array(
            'product_id' => $queryArgs['product_id'],
            'product_type' => $typeRel[$queryArgs['product_type']],
            'user_id' => $queryArgs['user_id'],
            'price' => $price,
            'count' => $queryArgs['product_count'],
            'create_time' => date('Y-m-d H:i:s', $now),
            'client' => $queryArgs['terminal_type'],
            'platform_order' => '',
            'success' => $isFree ? 1 : 0,
            'platform' => '',
            'invite_user_id' => $inviteUser,
            'has_express' => !empty($exist->need_address) ? 1 : 0
        );
        if (!empty($queryArgs['channel'])) {
            $order['channel'] = $queryArgs['channel'];
        }

        if (property_exists($exist, 'is_for_scramble') && $exist->is_for_scramble) {
            $order['is_for_scramble'] = $exist->is_for_scramble;
        }

        //待抢购的直播课,订单特殊处理
        if ($queryArgs['product_type'] == 'live_course' && $exist->is_limited && $exist->valid_order_period) {
            $invalidTime = $now + $exist->valid_order_period * 60; //订单失效时间
            $order['invalid_time'] = date('Y-m-d H:i:s', $invalidTime); //设置订单的过期时间
        }

        $result = $cmsdb->insert('original_orders', $order);
        $orderNum = $cmsdb->lastInsertId();

        if ($isFree) { //免费商品直接购买成功
            $cmsdb->insert('relation_user_product', array(
                'user_id' => $queryArgs['user_id'],
                'product_id' => $queryArgs['product_id'],
                'order_id' => $orderNum,
                'order_time' => date('y-m-d H:i:s'),
                'product_type' => $typeRel[$queryArgs['product_type']],
                'channel' => 6
            ));

            if ($queryArgs['product_type'] == 'live_course') {
                updateCoursePurchasedPersons($queryArgs['product_id'], 1);

                if ($order['has_express']) { //需要物流信息
                    $cmsdb->insert('express_tasks', array(
                        'rup_id' => $cmsdb->lastInsertId(),
                        'user_id' => $queryArgs['user_id'],
                        'express_num' => '',
                        'express_type' => '',
                        'create_time' => date('Y-m-d H:i:s'),
                        'status' => 0,
                        'course_id' => $queryArgs['product_id'],
                        'batch_no' => '',
                        'available' => 1
                    ));
                }
            }
        }

        //订单创建失败
        if (empty($result))
            return genOutput(8000);

        //订单信息缓存(object格式),20分钟
        $order['order_id'] = $orderNum;
        $cacheKey = 'orderInfo:'.$orderNum;
        cacheAdd($cacheKey, (object)$order, 20*60);

        return genOutput(1, array(
            'order_num' => strval($orderNum),
            'is_free' => $isFree,
            'invalid_time' => isset($order['invalid_time']) ? $order['invalid_time'] : '',
            'product_info' => array(
                'id' => intval($exist->id),
                'name' => $exist->name,
                'price' => $price,
                'valid_order_period' => !empty($exist->valid_order_period) ? $exist->valid_order_period * 60 : 0,
                'valid_pay_period' => !empty($exist->valid_pay_period) ? $exist->valid_pay_period * 60 : 0,
            )
        ));
    }

}